package com.yizisu.playerlibrary.view.video_view.helper


import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.provider.Settings
import android.view.View
import com.yizisu.playerlibrary.PlayerLibInit.Companion.app
import com.yizisu.playerlibrary.R
import kotlin.math.abs
import android.os.Looper
import android.util.Log
import android.util.TypedValue
import androidx.lifecycle.MutableLiveData
import com.yizisu.playerlibrary.BuildConfig
import kotlin.math.max

internal fun isMainThread() = Looper.getMainLooper() === Looper.myLooper()

internal fun <T> MutableLiveData<T>.updateValue(t: T?) {
    if (isMainThread()) {
        value = t
    } else {
        postValue(t)
    }
}


internal fun Activity.setScreenBrightnessSlide(offSet: Float): Float {
    val mBrightnessData = getCurrentBrightnessSlide()
    val lpa = window.attributes
    lpa.screenBrightness = mBrightnessData + offSet
    if (lpa.screenBrightness > 1.0f) {
        lpa.screenBrightness = 1.0f
    } else if (lpa.screenBrightness < 0f) {
        lpa.screenBrightness = 0f
    }
    window.attributes = lpa
    return lpa.screenBrightness
}

internal fun Activity.getCurrentBrightnessSlide(): Float {
    var screenBrightness = window.attributes.screenBrightness
    if (screenBrightness < 0f || screenBrightness > 1f) {
        screenBrightness =
            Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS) / 225f
    }
    return screenBrightness
}


/**
 * return 当前音量百分比
 */
private val audioManager by lazy { app.getSystemService(Context.AUDIO_SERVICE) as AudioManager }

/**
 * 音量调节
 */
internal fun View.setVolume(offSet: Float/*每次滑动距离百分比，不是总的滑动距离百分比*/): Float {
    val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
    val saveOffVolume = getTag(R.id.tag_save_current_volume)
    //当前变化的音量
    val offVolume = if (saveOffVolume is Float) {
        saveOffVolume + offSet * max
    } else {
        offSet * max
    }
    val lastVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)

    var newVolume = if (abs(offVolume) > 1f) {
        //变化值已经大于1，可以调节音量
        val split = offVolume.toString().split(".")
        //保存剩余没用消耗值
        setTag(R.id.tag_save_current_volume, "0.${split[1]}".toFloat())
        lastVolume + split[0].toInt()
    } else {
        setTag(R.id.tag_save_current_volume, offVolume)
        lastVolume
    }
    newVolume = when {
        newVolume < 0 -> {
            setTag(R.id.tag_save_current_volume, null)
            0
        }
        newVolume > max -> {
            setTag(R.id.tag_save_current_volume, null)
            max
        }
        else -> {
            newVolume
        }
    }
    if (newVolume != lastVolume) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0)
    }
    return newVolume / max.toFloat()
}

internal fun View.dip(value: Float): Float {
    val displayMetrics = resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, displayMetrics)
}

internal fun View.dip(value: Int): Int {
    return dip(value.toFloat()).toInt()
}
var playerLibDebug=BuildConfig.DEBUG
/**
 * 打印日志
 */
internal fun Any.logI(message: String?) {
    if (playerLibDebug ){
        Log.i(javaClass.simpleName, message ?: "null")
    }
}
/**
 * 毫秒换成00:00:00
 */
internal fun getCountTimeByLong(time: Long): String {
    val finishTime = max(time, 0L)
    var totalTime = (finishTime / 1000).toInt()//秒
    var hour = 0
    var minute = 0
    var second = 0

    if (3600 <= totalTime) {
        hour = totalTime / 3600
        totalTime -= 3600 * hour
    }
    return getCountTimeByLong(finishTime, hour > 0)
}

/**
 * 毫秒换成00:00:00
 */
internal fun getCountTimeByLong(finishTime: Long, isNeedHour: Boolean): String {
    if (finishTime <= 0) {
        return if (isNeedHour) {
            "00:00:00"
        } else {
            "00:00"
        }
    }
    var totalTime = (finishTime / 1000).toInt()//秒
    var hour = 0
    var minute = 0
    var second = 0

    if (3600 <= totalTime) {
        hour = totalTime / 3600
        totalTime -= 3600 * hour
    }
    if (60 <= totalTime) {
        minute = totalTime / 60
        totalTime -= 60 * minute
    }
    if (0 <= totalTime) {
        second = totalTime
    }
    val sb = StringBuilder()
    if (isNeedHour) {
        if (hour < 10) {
            sb.append("0").append(hour).append(":")
        } else {
            sb.append(hour).append(":")
        }
    }
    if (minute < 10) {
        sb.append("0").append(minute).append(":")
    } else {
        sb.append(minute).append(":")
    }
    if (second < 10) {
        sb.append("0").append(second)
    } else {
        sb.append(second)
    }
    return sb.toString()
}